import React,{useEffect, useRef, useState} from "react";
import {Tabs,Form,Select,Input,Tooltip,Button,Image,Tag,message,notification,Modal} from 'antd'
import LlxForm from 'components/LlxForm/index'
import classNames from "classnames";
import { connect } from 'react-redux'
import {setPageData,addHistoryRouter,setDictionaries,checkPublishData} from 'redux/action'
import LlxTable from 'components/LlxTable'
import {getVideoAblumPool,getVideoPool,getAllPool,pushPool,delPoolData,queryPageAllPool} from 'api/index'
import PushVideo from 'components/LlxPushData/video'
import PushAlbum from 'components/LlxPushData/videoAlbum'
// import PreviewVideo from 'components/LlxPreview/video'
const {TabPane} = Tabs
const {Search} = Input



const ClassifyData = (props) => {
  const {isModalVisible, setIsModalVisible,dataId,form,options,type} = props

  const loading = useRef(false)

  const [formItems] = Form.useForm()
  
  // 新增表单
const newWordItem = [
  {label: '电影院分类',name: 'poolId' , span: 20, rules:[
    {
      required: true,
      message: '请选择电影院分类'
    },
  ],render: () => {
    return <Select
    allowClear
    optionFilterProp="poolName"
    showSearch
    fieldNames={{value:'id',label:'poolName'}}
    placeholder={'请选择电影院分类'}
    options= {options}
  >
  </Select>
  } }
]

  const handleOk = () => {
    if(loading.current) return
    
    loading.current=true
    formItems.validateFields().then(async()=>{

      await pushPool({
        dataId: dataId,
        levelId: form.getFieldValue().levelId || 106,
        poolId: formItems.getFieldValue().poolId,
        type: type
      })
    
      notification.success({
        message: '添加成功',
        duration:1
      });

      form.resetFields()
      setIsModalVisible(false);

      props.getNewList()
    }).catch(err=>{
      console.log(err);
    }).finally(()=>{
      loading.current=false
    })
  };

  const handleCancel = () => {
    formItems.resetFields()
    setIsModalVisible(false);
  };

  return   <Modal width={700} title="选择电影院分类" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
        <LlxForm form={formItems} labelCol={8} formItem={newWordItem} />
   </Modal>
}



function VideoPool(props) {

const {dictionaries} = props
const userName = props.userInfo.userName
const [form] = Form.useForm()
const [loading,setLoading] = useState(false)
const [total,setTotal] = useState(false)
// const [isModalVisiblePreivew,setIsModalVisiblePreivew] = useState(false)
const [isModalVisiblePushVideo,setIsModalVisiblePushVideo] = useState(false)
const [isModalVisiblePushAlbum,setIsModalVisiblePushAlbum] = useState(false)
const [isModalVisibleClassify,setIsModalVisibleClassify] = useState(false)
const [tabIndex,setTabIndex] = useState('1')
// const [videoInfo,setVideoInfo] = useState({})
const [dataId,setDataId] = useState({})
const [type,setType] = useState('')
//分页数据
const [pagination,setPagination] = useState({
  current:1,
  pageSize:20
})
//初始表格数据
const [dataSource,setDataSource] = useState([])
const columns = [
  {title: '名称',fixed:'left', dataIndex: 'videoName',width:250, key: 'videoName', align: 'center',render: (text, record) => {
    return <div className="operate_link_group text-nowrap text-link" onClick={()=>goInfo(record)}>
      {text}
   </div>
 }},
 {title: '素材状态', dataIndex: 'upperLowerName',width:100, key: 'upperLowerName', align: 'center',render: (text, record) => {
  return <div className="operate_link_group text-nowrap">
    {
      text==='已上架'?<Tag  color="success">{text}</Tag>:<Tag  color="red">{text}</Tag>
    }
 </div>}},
  {title: '封面', dataIndex: 'pictureUrl',width:150, key: 'pictureUrl', align: 'center',render:(text)=>{
    return  <div>
      {
        text?<Image
        width={60}
        src={text}
      />:''
      }
    </div>
  }},
  {title: '类型', dataIndex: 'type',width:100, key: 'type', align: 'center'},
  {title: '适合年纪', dataIndex: 'ageName',width:100, key: 'ageName', align: 'center'},
  {title: '发行方', dataIndex: 'publisher',width:150, key: 'publisher', align: 'center'},
  {title: '主题', dataIndex: 'themes',width:180, key: 'themes', align: 'center', render: (text, record) => {
    return <div className="operate_link_group text-nowrap">
     {record.themes?.map((i,j)=>{
       return   <Tooltip key={i.id} placement="top" title={text.map(i=>i.themeName).join(' ')}>
        {
          j<3?<Tag key={i.id} color="lime">{i.themeName}</Tag>:''
        }
         </Tooltip>
     })}
   </div>}
  },
  {title: '系列', dataIndex: 'serialName',width:150, key: 'serialName', align: 'center'},
  {title: '类型', dataIndex: 'videoCategoryName',width:150, key: 'videoCategoryName', align: 'center'},
  {title: '标签', dataIndex: 'labels', key: 'labels',width:180, align: 'center', render: (text, record) => {
   return <div className="operate_link_group text-nowrap">
    {record.labels?.map((i,j)=>{
      return   <Tooltip key={i.id} placement="top" title={text.map(i=>i.labelName).join(' ')}>
       {
         j<3?<Tag key={i.id} color="green">{i.labelName}</Tag>:''
       }
        </Tooltip>
    })}
  </div>
}},
  {title: '创建人',width:120, dataIndex: 'createBy', key: 'createBy', align: 'center',render: (text, record) => {
    return <div className={classNames(userName===text?'operate_link_group text-nowrap text-color-red':"operate_link_group text-nowrap")}>
      {text}
   </div>
 }},
  {title: '更新人',width:120, dataIndex: 'updateBy', key: 'updateBy', align: 'center',render: (text, record) => {
    return  <div className={classNames(userName===text?'operate_link_group text-nowrap text-color-red':"operate_link_group text-nowrap")}>
    {text}
 </div>
 }},
  {title: '更新时间', dataIndex: 'updateTime', key: 'updateTime', align: 'center',width:180},
]

// 表单数据
const formItem = [
  {label: '类型', name: 'type', span: 4,render: () => {
    return <Select
    optionFilterProp="dictValue"
    showSearch
    fieldNames={{value:'id',label:'dictValue'}}
    placeholder={'请选择类型'}
    defaultValue={3}
    options={[{dictValue:'全部',id:3},{dictValue:'视频',id:1},{dictValue:'专辑',id:2}]}
  >
  </Select>
}},
{label: '级别', name: 'levelId', span: 4,render: () => {
  return <Select
  defaultValue={106}
  optionFilterProp="dictValue"
  showSearch
  fieldNames={{value:'id',label:'dictValue'}}
  placeholder={'请选择级别'}
  options={dictionaries.Level}
>
</Select>
}},
{label: '素材状态', name: 'upperLower', span: 4,render: () => {
  return <Select
  allowClear
  optionFilterProp="dictValue"
  showSearch
  fieldNames={{value:'id',label:'dictValue'}}
  placeholder={'请选择状态'}
  options={[{dictValue:'已上架',id:1010},{dictValue:'已下架',id:1000}]}
>
</Select>
}},
{label: '创建人', name: 'createBy',  span: 4 ,render: () => {
  return <Select
  allowClear
  optionFilterProp="userName"
  showSearch
  fieldNames={{value:'userName',label:'userName'}}
  placeholder={'请选择创建人'}
  options={dictionaries.UserSpecies}
>
</Select>
}},
{label: '', name: 'name' , span: 4,render: () => {
    return  <Search placeholder="请输入关键词搜索" onSearch={getNewList} enterButton />
} }
]
//选择数据
const [selectedRowKeys,setselectedRowKeys] = useState([])
const rowSelection  = useRef({
  selectedRowKeys: selectedRowKeys,
  onChange: value => {
  setselectedRowKeys(value)
  rowSelection.current.selectedRowKeys = value
  }
})
// 分类数据
const [classificationList,setClassificationList] = useState([])

// 初始化
//1缓存页面数据 缓存表单数据
useEffect(()=>{
  form.setFieldsValue(props.tabList.filter(i=>i.url==='areaPush/areaPushVideoLibrary')[0]?.data?.form)
  setPagination(props.tabList.filter(i=>i.url==='areaPush/areaPushVideoLibrary')[0]?.data?.pagination||{
    current:1,
    pageSize:20
  })
  },[]) // eslint-disable-line react-hooks/exhaustive-deps

// 1.切换tab
const callback = (key)  => {
    setTabIndex(key)
    setPagination({
      current:1,
      pageSize:20
    })
}
// 1.1
  useEffect(()=>{
    getNewList()
  },[tabIndex]) // eslint-disable-line react-hooks/exhaustive-deps

  // 2.获取数据
  const getNewList = async(value) => {
    setIsModalVisiblePushVideo(false)
    setIsModalVisiblePushAlbum(false)
     // 清空选中状态
   setselectedRowKeys(()=>[])
   rowSelection.current.selectedRowKeys=[]

   setLoading(true)
    // 缓存数据
   const data = {
    pagination: value&&value.pageSize?value:pagination,
    form:form.getFieldValue(),
    tab:1
   }
   props.setPageDataFn('areaPush/areaPushVideoLibrary',data) 

   // 获取tab分类数据
  const res = await getAllPool()
  setClassificationList([{poolName:'全部',id:'1'},...res.result[2].configList])

   const params = {
    currPage:value&&value.pageSize?value.current:pagination.current,
    pageSize:value&&value.pageSize?value.pageSize:pagination.pageSize,
    createBy:form.getFieldValue().createBy,
    levelId:form.getFieldValue().levelId || 106,
    videoName:form.getFieldValue().videoName,
    albumVideoName:form.getFieldValue().videoName,
    upperLower:form.getFieldValue().upperLower,
    poolId:tabIndex==='1'?'':tabIndex
  }
    
   if(form.getFieldValue().type===1){
    const res1 = await getVideoPool(params)

    const data1 = res1.result.records || []

    data1.forEach((i,j)=>{
      i.sort=j+1
      i.type='视频'
    })

    setDataSource(()=>data1)
  
    setTotal(res1.result.total)
  
    setLoading(false)
   } else  if(form.getFieldValue().type===2){
    const res1 = await getVideoAblumPool(params)
    
    const data1 = res1.result.records || []

    data1.forEach((i,j)=>{
      i.sort=j+1
      i.videoName = i.albumVideoName
      i.type='视频专辑'
    })

    setDataSource(()=>data1)
  
    setTotal(res1.result.total)
  
    setLoading(false)
   }  else {
    const res1 = await queryPageAllPool(params)
    
    const data1 = res1.result.records || []

    data1.forEach((i,j)=>{
      i.sort=j+1
    })

    setDataSource(()=>data1)
  
    setTotal(res1.result.total)
  
    setLoading(false)
   }
    
    
  }
//  3.去详情
const goInfo = (value) => {
  props.checkPublishDataBtn()
switch(value.type) {
  case '视频':
    props.history.push('/view/video/videoInfo?id=' + value.id)
    props.addRouter({
      menuName:'视频详情',url:'video/videoInfo?id=' + value.id 
    })
  break
  case '视频专辑':
    props.history.push('/view/video/videoAlbumInfo?id=' + value.id)
    props.addRouter({
      menuName:'专辑详情',url:'video/videoAlbumInfo?id=' + value.id 
    })
  break
  default:
    return
  }
}
// 4.拉取视频或者专辑数据
const pushVideoPool = (value) => {
  if(value==='video'){
    setIsModalVisiblePushVideo(true)
  } else {
    setIsModalVisiblePushAlbum(true)
  }
}
//  5.移除
const delPoolDatas = async() => {
  const data = dataSource.filter((i)=>selectedRowKeys.includes(i.sort)).map(i=>i.pushPoolId)
  for (let i = 0; i < data.length; i++) {
    await delPoolData(data[i])
  }
    message.success('移除成功')
   getNewList()
}
// 6.视频
const returnVideoId = (value) => {
  setDataId(value.map(i=>i.id))
  setType('VIDEO')
  setIsModalVisibleClassify(true)
}

// 7.专辑
const returnAlbumId  = (value) => {
  setDataId(value)
  setType('ALBUM_VIDEO')
  setIsModalVisibleClassify(true)
}
return  <div  className="app-content animate__animated animate__fadeIn overflow">

<LlxForm form={form} formItem={formItem}/>

<div className="operate-btn">
 <div>
       <Button  onClick={()=>pushVideoPool('video')} type='primary' className='animate__animated animate__fadeInLeft'>新增视频</Button>
       <Button  onClick={()=>pushVideoPool('album')} type='primary' className='animate__animated animate__fadeInLeft'>新增专辑</Button>
       <Button danger onClick={delPoolDatas} disabled={!selectedRowKeys.length} type='primary' className='animate__animated animate__fadeInLeft'>移除推送池</Button>
   </div>
</div>

<Tabs  activeKey={tabIndex} onChange={callback} className="app-content animate__animated animate__fadeIn">
  {
    classificationList.map((i,j)=>{
      return  <TabPane tab={i.poolName} key={i.id}>
      <LlxTable
      loading={loading} 
      pagination={pagination}
      setPagination={setPagination}
      selectedRowShow={true}
      keyName={'sort'}
      rowSelection={rowSelection.current}
      height={365}
      total={total}
      getNewList={getNewList}
      columns={columns}
      dataSource={dataSource}/>
   </TabPane>
    })
  }
</Tabs>


    <PushVideo returnSelect={returnVideoId} title={'电影院新增视频'} multipleType={true} userName={props.userInfo.user.userName} dictionaries={props.dictionaries} isModalVisible={isModalVisiblePushVideo} setIsModalVisible={setIsModalVisiblePushVideo}></PushVideo>
    <PushAlbum returnAlbumId={returnAlbumId} title={'电影院新增专辑'} multipleType={true} userName={props.userInfo.user.userName} dictionaries={props.dictionaries} isModalVisible={isModalVisiblePushAlbum} setIsModalVisible={setIsModalVisiblePushAlbum}></PushAlbum>
    
    {/* <PreviewVideo videoInfo={videoInfo}  isModalVisible={isModalVisiblePreivew} setIsModalVisible={setIsModalVisiblePreivew}></PreviewVideo> */}

    <ClassifyData  type={type} getNewList={getNewList} form={form} dataId={dataId} options={classificationList.filter(i=>i.poolName!=='全部')} isModalVisible={isModalVisibleClassify} setIsModalVisible={setIsModalVisibleClassify}></ClassifyData>

 </div>
}


// 映射方法
const mapDispatchToProps = (dispatch) => {
  return {
    checkPublishDataBtn: () => dispatch(checkPublishData()),
    addRouter: (route) => dispatch(addHistoryRouter(route)),
    setPageDataFn: (url,data) => dispatch(setPageData(url,data)),
    setDictionaries: (url,data) => dispatch(setDictionaries(url,data))
  }
}

export default connect((state)=>{
  return {tabList:state.tabList,examineStatus:state.examineStatus,userInfo:state.userInfo,dictionaries:state.dictionaries}
},mapDispatchToProps)(VideoPool)
